require "event_editor/gadgets/switch_button"
require 'gadgets/combobox'

module EventEditor
  module Conditions
    class Variable < Gtk::VBox
      
      def initialize(base, model)
        super()
        @model = model
        @operators = [['>', '>'], ['>=', '>='],['==', '=='], ['<=', '<='], ['<', '<']]
        @@operands = {}
        vbox = Gtk::VBox.new
        @@variable_input = EventEditor::Gadgets::SwitchButton.new(base, @model.variables) do |arr|
          @model.variables = arr
        end
        box = Gtk::HBox.new
        box.pack_start(@@variable_input, false, false)
        box.pack_start(Gtk::Label.new("is"))
        @@combobox = ::Gadgets::Combobox.new(@operators, [String, String])
        box.pack_start(@@combobox, false, false)
        
        vbox.pack_start(box, false, false)
        vbox.add(self.operand_chooser(base))
        
        self.add(vbox)
      end
      
      def operand_chooser(base)
        #frame = Gtk::Frame.new('Operands')
        @@operand_group = ::Gadgets::RadioGroup.new(:vertical)
        
        @@operands["var"] = EventEditor::Gadgets::SwitchButton.new(base, @model.variables) do |arr|
          @model.variables = arr
        end
        @@operand_group.add_element("var", "", @@operands["var"])
        
        @@operands["val"] = Gtk::SpinButton.new(0, 99999, 1)
        @@operand_group.add_element("val", "", @@operands["val"])
        
        #frame << @@operand_group
        return @@operand_group
      end
      
      def commands
        return ['variable', @@variable_input.value, @@combobox.selected_data, @@operand_group.selected_key, @@operands[@@operand_group.selected_key].value.to_i]
      end
      
      def self.load(command)
        @@variable_input.switch_no = command[1]
        @@combobox.select(command[2])
      end
      
      def self.load(edit_command)
        unless edit_command.empty?
          @@variable_input.value = edit_command[1]
          @@combobox.select(edit_command[2])
          @@operand_group.selected_key = edit_command[3]
          @@operands[edit_command[3]].value = edit_command[4]
        end
      end
      
      def self.command_to_s(model, args)
        s = ""
        s += '<b>Variable:</b> '
        t = args[2].clone
        t.gsub!(/>/, '＞')
        t.gsub!(/</, '＜')
        
        s += "[" + args[1].to_s + ": " + model.variables[args[1]] + "]" + " #{t} "

        case args[3]
        when "var"
          s += "[" + args[4].to_s + ": " + model.variables[args[4].to_i] + "]"
        else
          s += args[4].to_s
        end
        return s
      end
    end
  end
end